package com.dalianpai.gulimall.ware.listen;

import com.dalianpai.common.to.mq.OrderTo;
import com.dalianpai.common.to.mq.StockLockedTo;
import com.dalianpai.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author WGR
 * @create 2020/8/6 -- 20:54
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    @SneakyThrows
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel){
        System.out.println("收到解锁库存的消息");
        try{
            //当前消息是否被第二次及以后发送过来的
            message.getMessageProperties().getRedelivered();

            wareSkuService.unLockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @SneakyThrows
    @RabbitHandler
    public void handleStockOrderRelease(OrderTo to, Message message, Channel channel){
        System.out.println("订单关闭准备解锁库存。。。。");
        try{
            wareSkuService.unLockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
